local test = UnitTest:New("04DongleMessage")
local Dongle = DongleStub("Dongle-1.0")

function test:dongle_trigger_message()
	assert_fails(function() Dongle:TriggerMessage(1) end, argerror(2))
	local kappa = Dongle:New("Kappa")
	local lambda = Dongle:New("Lambda")
	
	local kappaalpha = kappa:NewModule("Kappa-Alpha")
	local lambdaalpha = lambda:NewModule("Lambda-Alpha")
	
	local triggered = {}
	local function onevent(self, event)
		triggered[self] = true
	end
	
	kappa:RegisterMessage("DONGLE_TEST_MESSAGE")
	kappa.DONGLE_TEST_MESSAGE = onevent
	lambdaalpha:RegisterMessage("DONGLE_TEST_MESSAGE")
	lambdaalpha.DONGLE_TEST_MESSAGE = onevent
	
	Dongle:TriggerMessage("DONGLE_TEST_MESSAGE")
	assert(triggered[kappa])
	assert(not triggered[lambda])
	assert(not triggered[kappaalpha])
	assert(triggered[lambdaalpha])
end

function test:dongle_register_message()
	assert_fails(function() Dongle:RegisterMessage(1) end, argerror(2))
	assert_fails(function() Dongle:RegisterMessage("hello", 1) end, argerror(3))
	local mu = Dongle:New("Mu")
	mu:RegisterMessage("DONGLE_TEST_MESSAGE")
end

function test:dongle_unregister_message()
	local nu = Dongle:New("Nu")
	assert_fails(function() Dongle:UnregisterMessage(1) end, argerror(2))
	nu:RegisterMessage("DONGLE_TEST_MESSAGE")
	nu:UnregisterMessage("DONGLE_TEST_MESSAGE")	
end

function test:dongle_ismessageregistered()
	local dongle = Dongle:New("MessageRegistered")
	assert_fails(function() Dongle:IsMessageRegistered(1) end, argerror(2))
	assert_fails(function() Dongle:IsMessageRegistered(nil) end, argerror(2))
	dongle:RegisterMessage("DONGLE_TEST_MESSAGE")
	assert(dongle:IsMessageRegistered("DONGLE_TEST_MESSAGE"))
	dongle:UnregisterMessage("DONGLE_TEST_MESSAGE")
	assert(not dongle:IsMessageRegistered("DONGLE_TEST_MESSAGE"))
end

function test:dongle_unregisterallevents()
	local xi = Dongle:New("Xi")
	xi:RegisterMessage("DONGLE_TEST1")
	xi:RegisterMessage("DONGLE_TEST2")
	local used = {}
	
	local function event(self, event)
		used[event] = true
	end
	
	xi.DONGLE_TEST1 = event
	xi.DONGLE_TEST2 = event
	xi.DONGLE_TEST3 = event
	
	xi:UnregisterAllMessages()
	xi:RegisterMessage("DONGLE_TEST3")
	Dongle:TriggerMessage("DONGLE_TEST1")
	Dongle:TriggerMessage("DONGLE_TEST2")
	Dongle:TriggerMessage("DONGLE_TEST3")
	assert(not used.DONGLE_TEST1)
	assert(not used.DONGLE_TEST2)
	assert(used.DONGLE_TEST3)
end

test:Run()